package com.zhongxi.guoyuan.view.personalCenter;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinShop.CoinOrderAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.CoinOrderData;
import com.zhongxi.guoyuan.entity.coinStore.CoinOrderResult;
import com.zhongxi.guoyuan.entity.user.center.UserCenterResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CoinOrderActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private ImageView ivUserHead;
    private TextView tvUserName;
    private TextView tvUserPhone;
    private TextView tvBonusPoint;
    private TextView tvIdentify;
    private TextView tvTime;
    private PullToRefreshListView lvList;
    private String type;
    private List<CoinOrderData> data = new ArrayList<>();
    private static Map<String, String> map = new HashMap<String, String>();
    private CoinOrderAdapter adapter;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            map.clear();
            type = "complain";
            map.put("shopid",data.get(msg.arg1).getShopid());
            map.put("orderid",data.get(msg.arg1).getId());
            map.put("content", (String) msg.obj);
            getServer(Url.TO_COMPLAIN, map, "", false, null, "post");
        }
    };
    private ImageView ivBox;
//    private TextView tvUpdate;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_coin_order);
        initTitle();
        tvTitle.setText("银币商家消费列表");
        ivUserHead = (ImageView) findViewById(R.id.ivUserHead);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvUserPhone = (TextView) findViewById(R.id.tvUserPhone);
        tvBonusPoint = (TextView) findViewById(R.id.tvBonusPoint);
        tvIdentify = (TextView) findViewById(R.id.tvIdentify);
        tvTime = (TextView) findViewById(R.id.tvTime);
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);

        ivBox = (ImageView) findViewById(R.id.ivBox);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new CoinOrderAdapter(context, data, handler);
        lvList.setAdapter(adapter);
        type = "user";
        getServer(Url.USER_CENTER, null, "", false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        lvList.setOnRefreshListener(this);
        ivBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, BoxActivity.class);
                intent.putExtra("index", 1);
                startActivity(intent);
            }
        });
        /*tvUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAct(UpdateActivity.class);
            }
        });*/
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("user".equals(type)){
                UserCenterResult result = gson.fromJson(response, UserCenterResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                initViewData(result);
                getOrder();
            }else if("order".equals(type)){
                CoinOrderResult orderResult = gson.fromJson(response, CoinOrderResult.class);
                MyApplication.getInstance().setSpValue(orderResult.getSafeobj());
                if(pageNum == 1){
                    data.clear();
                }
                if(orderResult.getData().size()>0){
                    data.addAll(orderResult.getData());
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            }else if("complain".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                showShortToast("投诉成功!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        if("complain".equals(type)){
            showShortToast("投诉失败！");
        }
    }

    /**
     * 获取银币消费列表
     */
    private void getOrder() {
        type = "order";
        String str = "&page="+pageNum;
        getServer(Url.COIN_ORDER_LIST, null, str, false, null, "get");
    }

    private void initViewData(UserCenterResult result) {
        try{
            if(null!=result.getUserInfo().getShopname()&&!"".equals(result.getUserInfo().getShopname())){
                tvUserName.setText(result.getUserInfo().getShopname());
            }else{
                tvUserName.setText(R.string.app_name);
            }
            if(null!=MyApplication.getInstance().getPhone()&&!"".equals(MyApplication.getInstance().getPhone())){
                tvUserPhone.setText(MyApplication.getInstance().parseSecutiryKey(result.getUserInfo().getMphone()));
            }else{
                tvUserPhone.setText("");
            }
            int point = 0;
            String time = "";
            if (null != result.getRights() && result.getRights().size() > 0) {
                for (int i = 0; i < result.getRights().size(); i++) {
                    if (null != String.valueOf(result.getRights().get(i).getUsertype())) {
                        if (result.getRights().get(i).getUsertype() == 0) {  //股东
                            if (null != String.valueOf(result.getRights().get(i).getSharesnum()))
                                point += result.getRights().get(i).getSharesnum();
                        } else {                                                            //权益会员
                            if (null != String.valueOf(result.getRights().get(i).getSharesnum()))
                                point += result.getRights().get(i).getSharesnum();
                            if(null!=result.getRights().get(i).getEtime())
                                time+=result.getRights().get(i).getEtime();
                        }
                    }
                }
            }
            if (null != String.valueOf(point)) {
                tvBonusPoint.setText(String.valueOf(point));
            }else {
                tvBonusPoint.setText("0");
            }
            if(null!=time&&!"".equals(time)){
                tvTime.setText(time);
            }else{
                tvTime.setText("");
            }
            if(null!=result.getUserInfo().getAvatar()&&!"".equals(result.getUserInfo().getAvatar())){
//                ImageLoader.getInstance().displayImage(Url.BASE_URL+result.getUserInfo().getAvatar(), ivUserHead, CommonTool.getOptions(R.mipmap.iv_eg));
                Glide.with(context).load(Url.BASE_URL+result.getUserInfo().getAvatar()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(ivUserHead);
            }
            String sb = new String();
            /*if(null!=result.getUserInfo().getIsshareholders()){
                if("1".equals(result.getUserInfo().getIsshareholders())){
                    sb+="普通会员";
                }
            }*/
            if(null!=result.getUserInfo().getIsprivilege()){
                if("1".equals(result.getUserInfo().getIsprivilege())){
                    sb+="权益会员";
                }
            }
            if(null!=sb&&!"".equals(sb)){
                tvIdentify.setText(sb.toString());
            }else{
                tvIdentify.setText("普通会员");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getOrder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getOrder();
    }
}
